package _021_10_4

import "strings"

func licenseKeyFormatting(s string, k int) string {
	nAlphaNum := 0
	s = strings.ToUpper(s)
	for i := 0; i < len(s); i++ {
		if !isAlphaOrNum(s[i]) {
			nAlphaNum++
		}
	}
	l := len(s) - nAlphaNum
	if l == 0 {
		return ""
	}
	firstN := l % k
	if l%k == 0 {
		firstN = k
	}
	_firstN := 0
	result := ""
	strId := 0
	for ; _firstN < firstN; strId++ {
		if isAlphaOrNum(s[strId]) {
			result += string(s[strId])
			_firstN++
		}
	}
	if strId != len(s) {
		result += "-"
	}
	circleNum := 0
	for ; strId != len(s); strId++ {
		if isAlphaOrNum(s[strId]) {
			result += string(s[strId])
			if circleNum == k-1 && strId != len(s)-1 {
				circleNum = 0
				result += string("-")
				continue
			}
			circleNum++
		}
	}
	if result[len(result)-1] == '-' {
		result = result[:len(result)-1]
	}
	return result
}

func isAlphaOrNum(c byte) bool {

	if 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' {
		return true
	}
	return false
}
